package com.cash.loan.modular.cash.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.cash.loan.common.result.PageResult;
import com.cash.loan.common.upload.QiniuService;
import com.cash.loan.common.util.PageBeanUtil;
import com.cash.loan.common.util.RedisUtil;
import com.cash.loan.core.util.RandomUtil;
import com.cash.loan.modular.cash.dao.LoanProductDetailMapper;
import com.cash.loan.modular.cash.dao.LoanProductMapper;
import com.cash.loan.modular.cash.model.LoanProduct;
import com.cash.loan.modular.cash.service.ProductService;
import com.cash.loan.modular.cash.transfer.vo.ProductDetailMapVo;
import com.cash.loan.modular.cash.transfer.vo.ProductDetailVo;
import com.cash.loan.modular.cash.transfer.vo.ProductListVo;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @Date 2018-07-09 10:49
 */
@Service
public class ProductServiceImpl implements ProductService {

    private static final String APPLY_NUM_NAME = "apply_num";

    private static final Integer UI_TYPE = 2;

    @Autowired
    private LoanProductMapper productMapper;

    @Autowired
    private LoanProductDetailMapper detailMapper;

    @Autowired
    private QiniuService qiniuService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ProductIndexServiceImpl productIndexService;

    /**
     * 产品详情
     * @param productId
     * @return
     */
    @Override
    public ProductDetailMapVo productDetail(Integer productId) {
        ProductDetailMapVo mapVo = new ProductDetailMapVo();
        ProductDetailVo productDetailVo = productMapper.getLoanProductDetail(productId);

        if(productDetailVo == null) {
            return null;
        }

        mapVo.setProductName(productDetailVo.getProductName());

        mapVo.setProductIconUrl(qiniuService.getUrl(productDetailVo.getProductIconUrl()));

        mapVo.setProductH5Url(productDetailVo.getProductH5Url());

        mapVo.setDayLoanRate(productDetailVo.getDayLoanRate());

        mapVo.setLoanAmount(productDetailVo.getMinLoanAmount().toString()+"-"+productDetailVo.getMaxLoanAmount()+"元");

        StringBuilder dateTerm = new StringBuilder("");
        if(productDetailVo.getMinLoanTerm() > 30) {
            dateTerm.append(productDetailVo.getMinLoanTerm() / 30).append("月-");
        } else {
            dateTerm.append(productDetailVo.getMinLoanTerm()).append("天-");
        }
        if(productDetailVo.getMaxLoanTerm() > 30) {
            dateTerm.append(productDetailVo.getMaxLoanTerm() / 30).append("月");
        } else {
            dateTerm.append(productDetailVo.getMaxLoanTerm()).append("天");
        }
        mapVo.setLoanTerm(dateTerm.toString());

        JSONArray applyFlowList = JSONArray.parseArray(productDetailVo.getApplyFlowList());

        mapVo.setApplyFlowList(applyFlowList);

        mapVo.setApplyCondition(productDetailVo.getApplyCondition());

        mapVo.setAuditDetail(productDetailVo.getAuditDetail());

        mapVo.setProductIntroduce(productDetailVo.getProductIntroduce());

        mapVo.setApplyNum(getApplyNum(productId));

        return mapVo;
    }

    /**
     * 得到申请人数（缓存存放在hash数据结构中）
     * @param productId
     * @return
     */
    private Integer getApplyNum(Integer productId) {
        Integer applyNum = null;
        Boolean isExist = redisUtil.hasHashKey(APPLY_NUM_NAME,String.valueOf(productId));
        if(isExist) {
            applyNum = Integer.valueOf((String) redisUtil.getMap(APPLY_NUM_NAME,String.valueOf(productId)));
            redisUtil.incrementHashValue(APPLY_NUM_NAME,String.valueOf(productId),1L);
        } else {
            Random random = new Random();
            applyNum = RandomUtil.nextInt(random,50000,60000);
            redisUtil.setMap(APPLY_NUM_NAME,String.valueOf(productId),String.valueOf(applyNum));
        }
        return applyNum;
    }

    /**
     * 分页查询产品列表
     * @param currentPage
     * @param pageSize
     * @param minLoanTerm
     * @param maxLoanTerm
     * @param minLoanAmount
     * @param maxLoanAmount
     * @param orderBy
     * @return
     */
    @Override
    public PageResult<ProductListVo> getProductPageList(Integer currentPage, Integer pageSize, Integer minLoanTerm,
                                                        Integer maxLoanTerm, BigDecimal minLoanAmount,
                                                        BigDecimal maxLoanAmount, String orderBy,Integer cateId,Integer uiType) {
        PageHelper.startPage(currentPage,pageSize);
        List<LoanProduct> productList = productMapper.getProductByConditions(minLoanTerm,maxLoanTerm,
                minLoanAmount,maxLoanAmount,orderBy,cateId);

        if(productList == null || productList.size() == 0) {
            List<ProductListVo> list = new ArrayList<>();
            PageResult<ProductListVo> pageResult = new PageResult<>();
            pageResult.setDataList(list);
        }

        if(UI_TYPE.equals(uiType)) {
            productList = productList.stream()
                    .filter(loanProduct -> Integer.valueOf(0).equals(loanProduct.getDownloadFlag()))
                    .collect(Collectors.toList());
        }

        List<ProductListVo> productListVoList = new ArrayList<>();
        productList.stream().forEach(loanProduct -> {
            ProductListVo listVo = new ProductListVo();
            listVo.setProductId(loanProduct.getId());
            listVo.setProductName(loanProduct.getProductName());
            listVo.setProductIconUrl(qiniuService.getUrl(loanProduct.getProductIconUrl()));
            listVo.setProductH5Url(detailMapper.getH5Url(loanProduct.getProductId()));
            listVo.setProductSellPoint(loanProduct.getProductSellPoint());
            listVo.setDayLoanRate(loanProduct.getDayLoanRate());
            StringBuilder dateTerm = new StringBuilder("");
            if(loanProduct.getMinLoanTerm() > 30) {
                dateTerm.append(loanProduct.getMinLoanTerm() / 30).append("月-");
            } else {
                dateTerm.append(loanProduct.getMinLoanTerm()).append("天-");
            }
            if(loanProduct.getMaxLoanTerm() > 30) {
                dateTerm.append(loanProduct.getMaxLoanTerm() / 30).append("月");
            } else {
                dateTerm.append(loanProduct.getMaxLoanTerm()).append("天");
            }
            listVo.setLoanTerm(dateTerm.toString());
            listVo.setMaxLoanAmount(loanProduct.getMaxLoanAmount().toString());
            listVo.setMinLoanAmount(loanProduct.getMinLoanAmount().toString());
            productListVoList.add(listVo);
        });
        PageResult pageResult = PageBeanUtil.toPageResult(productList);
        pageResult.setDataList(productListVoList);
        return pageResult;
    }

    @Override
    public String getApplyPageUrl(Integer productId) {
        return productMapper.getApplyUrl(productId);
    }

    /**
     * 得到推荐口子
     * @return
     */
    @Override
    public List<Map<String, Object>> getRecommendProduct() {
        List<Map<String,Object>> recommendProductMapList = new ArrayList<>();
        List<LoanProduct> recommendLoanProductList = productMapper.getRecommendProduct();

        if(recommendLoanProductList == null || recommendLoanProductList.size() == 0) {
            return new ArrayList<>(1);
        }
        recommendProductMapList = productIndexService.dealProductInfo(recommendLoanProductList);
        return recommendProductMapList;
    }
}
